import React, { Component } from 'react'

import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Image,
  Dimensions,
  TouchableWithoutFeedback
} from 'react-native'

export default class BookList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      booksList: [],
      nextUrl: ''
    }
    this.handleRefresh = this.handleRefresh.bind(this)
    this.handleGoBack = this.handleGoBack.bind(this)
    this.navigateToBookInfo = this.navigateToBookInfo.bind(this)
  }
  handleRefresh () {
    const url = this.state.nextUrl
    this.fetchBookList(url).then(data => {
      if (data.code === 0) {
        this.setState({
          booksList: data.subjectBooklist,
          nextUrl: data.nextUrl
        })
      }
    })
    .catch(error => {
      console.error(error)
    })
  }
  fetchBookList (url) {
    return fetch(url)
      .then(res => {
        return res.json()
      })
      .catch(error => {
        console.error(error)
      })
  }
  handleGoBack () {
    const { navigation } = this.props
    navigation.goBack()
  }
  navigateToBookInfo (book) {
    const { navigation } = this.props
    navigation.navigate('BookInfo', book)
  }
  
  componentDidMount() {
    const { moduleId, entryId } = this.props.navigation.state.params
    const url = `http://p.du.163.com/bookstore/subject/more.json?moduleId=${moduleId}&entryId=${entryId}&page=1&pageSize=32`
    this.fetchBookList(url).then(data => {
      if (data.code === 0) {
        this.setState({
          booksList: data.subjectBooklist,
          nextUrl: data.nextUrl
        })
      }
    })
    .catch(error => {
      console.error(error)
    })
  }
  render () {
    const { title } = this.props.navigation.state.params
    const { booksList } = this.state
    return (
      <View style={{ flex: 1, justifyContent: 'flex-start',backgroundColor: '#fff'}}>
        <View style={styles.titleContainer}>
          <TouchableWithoutFeedback onPress={this.handleGoBack}>
            <View style={styles.backButtonContainer}>
              <Text style={styles.backButton}>返回</Text>
            </View>
          </TouchableWithoutFeedback>
          <View style={styles.reading}>
            <Text style={[styles.readingText]}>{title}</Text>
          </View>
        </View>
        <FlatList
          data={booksList}
          renderItem={({item}) =>
            <TouchableWithoutFeedback onPress={() => {this.navigateToBookInfo(item.book)}}>
              <View style={styles.bookItem}>
                <Image source={{uri: item.book.imageUrl}} style={styles.bookItemImage} />
                <Text style={styles.bookItemText}>{item.book.title}</Text>
              </View>
            </TouchableWithoutFeedback>
          }
          keyExtractor={(c, i) => i + ''}
          numColumns={3}
          columnWrapperStyle={styles.bookRowContainer}
          onEndReachedThreshold={0.35}
          onEndReached={this.handleRefresh}
        />
      </View>
    )
  }
}

const { width } = Dimensions.get('window')
const currentImageWidth = (width - 80 ) / 3
const currentImageHeight  =  800 / 600 * currentImageWidth
const fontColor = '#333'

const styles = StyleSheet.create({
  reading: {
    flexDirection: 'row',
    justifyContent: 'center',
    borderStyle: 'solid',
    borderBottomWidth: 1,
    borderColor: '#eee',
    overflow: 'hidden',
    height: 40
  },
  readingText: {
    height: 40,
    lineHeight: 40,
    fontWeight: 'bold',
    marginRight: 10
  },
  bookItem: {
    marginRight: 20,
    height: currentImageHeight + 40
  },
  bookRowContainer: {
    marginLeft: 20,
    marginTop: 15
  },
  bookItemImage: {
    width: currentImageWidth,
    height: currentImageHeight
  },
  bookItemText: {
    width: currentImageWidth,
    marginTop: 10,
    textAlign: 'left',
    fontSize: 10,
    color: fontColor
  },
  titleContainer: {
    position: 'relative',
    marginBottom: 3
  },
  backButtonContainer: {
    width: 60,
    position: 'absolute',
    top: 2,
    left: 20,
    zIndex: 2
  },
  backButton: {
    paddingTop: 10,
    paddingBottom: 10,
    fontSize: 12
  }
})